// pages/myReimbursement/index.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    selectData: [
      {
        'id': 0,
        'statusName': '综合办'
      },
      {
        'id': 1,
        'statusName': '交接处'
      },
      {
        'id': 2,
        'statusName': '工程部'
      },
      {
        'id': 3,
        'statusName': '已完成'
      }
    ],
    index: '',//选择的下拉列表下标
    ApprovalList: [],//流程审批列表
    name: '',
    reviewTel: '',
    money: '',
    fan: '',
    door: '',
    tube: '',
    inversion: '',
    transfer: '',
    window: '',
    pack: '', // 打包类目
    brandId: '', // 品牌
    materialId: '', // 型号
    asterisk: '',
    thicknessId: '', // 壁厚
    openId: '', // 开启
    tel: '',
    type: '',
    affiliated: '',
    isDelivery: '',
    isPlacement: '',
    isAudits: '',
    isPay: '',
    createTime: '',
    updateTime: '',
    createTime1: '',
    updateTime1: '',
    pageNum: 1,
    pageSize: 50,
    total: 0,
    deptId: "",
    isPages: true,
    pageSizeIndex: 1,
    columns: [
      { value: 0, name: 10 },
      { value: 1, name: 50 },
      { value: 2, name: 100 },
      { value: 6, name: 300 },
      { value: 3, name: 500 },
      { value: 4, name: 1000 },
      { value: 5, name: 5000 },
    ],
    admin: 0,
    bigAdmin: 0,
    totalMoney: 0,
    promise: false,
    searchTagList: [],
    allTotal: 0, // 总货款
    allCollection: 0, // 总收款
    allSurplus: 0, // 剩余款
    // allFan: 0,  // 开扇数量
    // allDoor: 0, // 开门数量
    // allTube: 0, // 方管数量
    // allInversion: 0, // 内倒数量
    // allTransfer: 0, // 转角数量
    // allWindow: 0, // 纱窗数量
    telphone: '15229883888',
    allList: [],
    active: [5],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      deptId: options.id,
      bigAdmin: wx.getStorageSync('admin'),
      admin: wx.getStorageSync('admin') == 1 || wx.getStorageSync('subAdmin') == 1 ? 1 : 0
    })
    this.getDate();
    this.getphone();
    wx.hideShareMenu();
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      pageNum: 1,
      pageSize: 50
    });
    this.childComponent = this.selectComponent("#moneySearch");
    this.childComponent.reset();
    this.getDepartmentList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      pageNum: 1,
      pageSize: 50,
      pageSizeIndex: 1
    });
    this.getDate();
    this.getphone();
    this.childComponent = this.selectComponent("#moneySearch");
    this.childComponent.reset();
    this.getDepartmentList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (!this.data.isPages) return;
    var pages = this.data.pageNum;
    var page = pages + 1;
    this.setData({ pageNum: page });
    this.getApprovalListData();//调用方法
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(res) {
    // let id = res.target.dataset.id;
    // console.log('onShareAppMessage',id);
    // return {
    //   title: '工单列表',
    //   path: `/pages/financialreview/index?id=${id}&dpId=${this.data.deptId}&share=true`
    // }
  },

  // TOO 财务审核页面
  toDetail(e) {
    if (e.currentTarget.dataset.is) {
      wx.showModal({
        title: '提示',
        content: '工单未审核,请联系管理员授权，否则不能进展！',
        cancelText: '马上联系',
        confirmText: '进入审核',
        complete: (res) => {
          if (res.confirm) {
            let id = e.currentTarget.dataset.id;
            // TOO  添加财务工单页面
            wx.navigateTo({
              url: `/pages/financialreview/index?id=${id}&dpId=${this.data.deptId}`
            })
          }

          if (res.cancel) {
            wx.makePhoneCall({
              phoneNumber: this.data.telphone,
              success() {
              },
            });
          }
        }
      })
    } else {
      let id = e.currentTarget.dataset.id;
      // TOO  添加财务工单页面
      wx.navigateTo({
        url: `/pages/financialreview/index?id=${id}&dpId=${this.data.deptId}`
      })
    }
  },

  toUpdate(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/updateFinancialReimbursement/index?id=${id}&dpId=${this.data.deptId}`
    })
  },

  showItem(item) {
    if(wx.getStorageSync('admin') == 1 || wx.getStorageSync('subAdmin') == 1) return true;
    if(item.status == '3' && (item.isDelivery != 1 || (item.isDelivery == 1 && wx.getStorageSync('userId') == item.deliveryUser))) return true;
    if(item.status != '3' && (item.isPlacement != 1 || (item.isPlacement == 1 && wx.getStorageSync('userId') == item.placementUser))) return true;
    return false;
  },

  // 获取待审核列表  传值搜索
  getApprovalListData() {
    wx.showLoading({
      title: '加载中...',
    });
    const { active, deptId } = this.data;
    let signData = {};
    if (this.data.deptId == 0) {
      signData = { sign1: active.includes(2) ? 0 : active.includes(3) ? 1 : '' };
    } else if (this.data.deptId == 2) {
      signData = { sign2: active.includes(2) ? 0 : active.includes(3) ? 1 : '' };
    } else if (this.data.deptId == 3) {
      signData = { sign3: active.includes(2) ? 0 : active.includes(3) ? 1 : '' };
    }
    const data = {
      name: this.data.name,
      tel: this.data.tel,
      reviewTel: this.data.reviewTel,
      // fan: this.data.fan,
      // door: this.data.door,
      money: this.data.money,
      // tube: this.data.tube,
      // inversion: this.data.inversion,
      // transfer: this.data.transfer,
      // window: this.data.window,
      // pack: this.data.pack, // 打包类目
      // brandId: this.data.brandId, // 品牌
      // materialId: this.data.materialId, // 型号
      asterisk: this.data.asterisk,
      // thicknessId: this.data.thicknessId, // 壁厚
      // openId: this.data.openId, // 开启
      type: this.data.type,
      createTime: this.data.createTime ? this.data.createTime : '',
      updateTime: this.data.updateTime ? this.data.updateTime : '',
      createTime1: this.data.createTime1 ? this.data.createTime1 : '',
      updateTime1: this.data.updateTime1 ? this.data.updateTime1 : '',
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize,
      affiliated: this.data.affiliated,
      isDelivery: deptId != 3 ? '' : active.includes(0) ? 0 : active.includes(1) ? 1 : '',
      isPlacement: deptId == 3 ? '' : active.includes(0) ? 0 : active.includes(1) ? 1 : '',
      ...signData,
    }
    if (this.data.deptId != 3) data.deptId = this.data.deptId;
    wx.request({
      url: this.data.deptId == 3 ? `${app.globalData.baseUrl}/api/finance/selFinishList` : `${app.globalData.baseUrl}/api/finance/selDeptList`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      data: data,
      success: (res) => {
        if (res.data.code != 0) return;
        let list = this.data.pageNum == 1 ? res.data.rows : this.quchong([...this.data.ApprovalList, ...res.data.rows]);
        const allList = this.data.pageNum == 1 ? res.data.rows : this.quchong([...this.data.allList, ...res.data.rows]);
        let flag = true;
        if (allList.length >= res.data.total) {
          flag = false;
        }
        let num = 0,
          allTotal = 0,
          allCollection = 0,
          allSurplus = 0;
          // allFan = 0,
          // allDoor = 0,
          // allTube = 0,
          // allInversion = 0,
          // allTransfer = 0,
          // allWindow = 0;
        list = list.filter(item => this.showItem(item));
        if (active.includes(4)) list = list.filter(item => (parseFloat(item.total || 0) + parseFloat(item.changeTotal || 0) - parseFloat(item.paid || 0)) > 0);
        list.forEach(item => {
          num += parseFloat(item.money);
          item.surplus = (parseFloat(item.total || 0) + parseFloat(item.changeTotal || 0) - parseFloat(item.paid || 0)).toFixed(2) || 0;
          allTotal = allTotal + parseFloat(item.total) + parseFloat(item.changeTotal);
          allCollection += parseFloat(item.paid);
          allSurplus += parseFloat(item.surplus);
          // allFan += parseFloat(item.fan * 100);
          // allDoor += parseFloat(item.door * 100);
          // allTube += parseFloat(item.tube * 100);
          // allInversion += parseFloat(item.inversion * 100);
          // allTransfer += parseFloat(item.transfer * 100);
          // allWindow += parseFloat(item.window * 100);
          item.totalShow = (parseFloat(item.total) + parseFloat(item.changeTotal)).toFixed(2);
          item.isAudits = this.data.deptId == 0 ? item.sign1 : this.data.deptId == 2 ? item.sign2 : this.data.deptId == 3 ? item.sign3 : '1';
          item.isOpen = true;
        });

        this.setData({
          allList,
          ApprovalList: list,
          isPages: flag,
          totalMoney: num,
          allTotal: allTotal.toFixed(2), // 总货款
          allCollection: allCollection.toFixed(2), // 总收款
          allSurplus: allSurplus.toFixed(2), // 剩余款
          // allFan: allFan > 0 ? (allFan / 100).toFixed(2) : '',  // 开扇数量
          // allDoor: allDoor > 0 ? (allDoor / 100).toFixed(2) : '', // 开门数量
          // allTube: allTube > 0 ? (allTube / 100).toFixed(2) : '', // 方管数量
          // allInversion: allInversion > 0 ? (allInversion / 100).toFixed(2) : '', // 内倒数量
          // allTransfer: allTransfer > 0 ? (allTransfer / 100).toFixed(2) : '', // 转角数量
          // allWindow: allWindow > 0 ? (allWindow / 100).toFixed(2) : '', // 纱窗数量
        });
        wx.hideLoading();
      }
    })
  },

  // 数据去重
  quchong(arr) {
    var tempArr = []; //返回的值
    var indexArr = []; //返回的索引
    for (var i = 0; i < arr.length; i++) {
      if (tempArr.indexOf(arr[i]) == -1) {
        tempArr.push(arr[i]);
        indexArr.push(i)
      } else if (tempArr.indexOf(arr[i]) >= 0) {
        for (var j = 0; j < tempArr.length; j++) {
          if (tempArr[j] == arr[i]) {
            tempArr.splice(j, 1, tempArr[j]);
            indexArr.splice(j, 1, i);
          }
        }
      }
    }
    return tempArr
  },

  onSelectPageSize(e) {
    this.setData({
      pageSizeIndex: e.detail.value,
      pageNum: 1,
      pageSize: this.data.columns[e.detail.value].name,
      isPages: true,
    });
    this.getApprovalListData();
  },

  processDelete(e) {
    let id = e.currentTarget.dataset.id;
    const that = this;
    wx.showModal({
      content: '确认删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          wx.request({
            url: `${app.globalData.baseUrl}/api/finance/del?id=${id}`,
            method: "GET",
            header: {
              'token': wx.getStorageSync('token'),
              "Content-Type": "application/json"
            },
            data: {},
            success: (res) => {
              if (res.data.code == 0) {
                that.getApprovalListData();
                wx.showToast({
                  title: '操作成功',
                });
              }
            }
          })
        } else {
          console.log('用户点击取消');
        }
      }
    })
  },

  onDisplay() {
    this.setData({ show: true });
  },

  onClose() {
    this.setData({ show: false });
  },

  search(e) {
    const form = e.detail.form;
    const nameObj = e.detail.nameObj;
    this.setData({
      ...form,
      pageNum: 1,
      show: false,
    });
    this.getApprovalListData();
    const arr = [];
    if (form.name) arr.push(`详细地址:${form.name}`);
    if (form.tel) arr.push(`联系电话:${form.tel}`);
    if (form.type) arr.push(`项目加工形态:${form.type}`);
    if (form.money) arr.push(`装修数量:${form.money}`);
    if (form.reviewTel) arr.push(`发起人和电话:${form.reviewTel}`);
    if (form.fan) arr.push(`开扇数量:${form.fan}`);
    if (form.door) arr.push(`开门数量:${form.door}`);
    if (form.tube) arr.push(`方管数量:${form.tube}`);
    if (form.inversion) arr.push(`内倒数量:${form.inversion}`);
    if (form.transfer) arr.push(`转角数量:${form.transfer}`);
    if (form.window) arr.push(`开扇纱窗数量:${form.window}`);
    if (nameObj.packName) arr.push(`打包类目:${nameObj.packName}`);
    if (nameObj.brandName) arr.push(`品牌:${nameObj.brandName}`);
    if (nameObj.materialName) arr.push(`型号:${nameObj.materialName}`);
    if (nameObj.thicknessName) arr.push(`壁厚:${nameObj.thicknessName}`);
    if (nameObj.openName) arr.push(`开启:${nameObj.openName}`);
    if (nameObj.affiliatName) arr.push(`隶属归类：${nameObj.affiliatName}`);
    if (form.createTime1) arr.push(`创建时间:${form.createTime1} - ${form.updateTime1}`);
    if (form.createTime) arr.push(`更新时间:${form.createTime} - ${form.updateTime}`);
    if (nameObj.asteriskName) arr.push(`星星状态：${nameObj.asteriskName}`);
    this.setData({ searchTagList: arr });
  },

  updateId(id, list) {
    let name = '';
    list.forEach(item => {
      if (id == item.dictCode) name = item.dictLabel;
    })
    return name;
  },

  resetIsPage() {
    this.setData({ isPages: true });
  },

  // 获取部门列表
  getDepartmentList() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/finance/getUserDept`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        if (res.data.code == 0) {
          const deptIds = [];
          res?.data?.data?.forEach(item => {
            deptIds.push(item.deptId);
          });
          this.setData({ promise: deptIds.indexOf(3) > -1 });
        }
      }
    })
  },

  isDeliveryChange(e) {
    const that = this;
    wx.showModal({
      content: e.detail ? '确定交付？请配好货物统计数量！去交付！' : '确定取消交付？',
      cancelText: '关闭',
      success: function (sm) {
        if (sm.confirm) {
          wx.request({
            url: `${app.globalData.baseUrl}/api/finance/update`,
            method: "POST",
            data: { id: e.currentTarget.dataset.id, isDelivery: e.detail ? 1 : 0 },
            header: {
              "Content-Type": "application/json",
              'token': wx.getStorageSync('token'),
            },
            success: function (res) {
              if (res.data.code == 0) {
                const arr = JSON.parse(JSON.stringify(that.data.ApprovalList));
                arr.forEach(item => {
                  if (item.id === e.currentTarget.dataset.id) {
                    item.isDelivery = e.detail ? 1 : '';
                  }
                });
                if (that.data.isDelivery === '') {
                  that.setData({ ApprovalList: arr });
                } else {
                  that.getApprovalListData();
                }
              } else {
                wx.showToast({
                  title: res.data.msg || '系统异常',
                })
              }
            },
            fail() {
              wx.showToast({
                title: '出错啦！',
                icon: 'error',
                duration: 2000
              })
            }
          })
        } else {
          console.log('用户点击取消');
        }
      }
    });
  },

  isPlacementChange(e) {
    if (e.currentTarget.dataset.is) {
      wx.showModal({
        title: '提示',
        content: '工单未审核,请联系管理员授权，否则不能进展！',
        cancelText: '马上联系',
        confirmText: '关闭',
        complete: (res) => {
          if (res.confirm) {}
          if (res.cancel) {
            wx.makePhoneCall({
              phoneNumber: this.data.telphone,
              success() {
              },
            });
          }
        }
      })
      return;
    }
    const that = this;
    wx.showModal({
      content: e.detail ? '确定我来处理！工单将不再展示给外人！只属于勾选人！请你用心维护好本次服务！' : '确定取消我来处理？',
      cancelText: '关闭',
      success: function (sm) {
        if (sm.confirm) {
          wx.request({
            url: `${app.globalData.baseUrl}/api/finance/update`,
            method: "POST",
            data: { id: e.currentTarget.dataset.id, isPlacement: e.detail ? 1 : 0 },
            header: {
              "Content-Type": "application/json",
              'token': wx.getStorageSync('token'),
            },
            success: function (res) {
              if (res.data.code == 0) {
                const arr = JSON.parse(JSON.stringify(that.data.ApprovalList));
                arr.forEach(item => {
                  if (item.id === e.currentTarget.dataset.id) {
                    item.isPlacement = e.detail ? 1 : '';
                  }
                });
                if (that.data.isPlacement === '') {
                  that.setData({ ApprovalList: arr });
                } else {
                  that.getApprovalListData();
                }
              } else {
                wx.showToast({
                  title: res.data.msg || '出错啦！',
                  icon: 'error',
                  duration: 2000
                })
              }
            },
            fail() {
              wx.showToast({
                title: '出错啦！',
                icon: 'error',
                duration: 2000
              })
            }
          })
        } else {
          console.log('用户点击取消');
        }
      }
    });
  },

  //审核标记
  isAuditsChange(e) {
    const that = this;
    let signData = {};
    if (this.data.deptId == 0) {
      signData = { sign1: e.detail ? '1' : '0' };
    } else if (this.data.deptId == 2) {
      signData = { sign2: e.detail ? '1' : '0' };
    } else if (this.data.deptId == 3) {
      signData = { sign3: e.detail ? '1' : '0' };
    }
    wx.showModal({
      content: e.detail ? '确定标记该工单吗？' : '确定取消标记该工单吗？',
      cancelText: '关闭',
      success: function (sm) {
        if (sm.confirm) {
          wx.request({
            url: `${app.globalData.baseUrl}/api/finance/update`,
            method: "POST",
            data: { id: e.currentTarget.dataset.id, ...signData },
            header: {
              "Content-Type": "application/json",
              'token': wx.getStorageSync('token'),
            },
            success: function (res) {
              if (res.data.code == 0) {
                const arr = JSON.parse(JSON.stringify(that.data.ApprovalList));
                arr.forEach(item => {
                  if (item.id === e.currentTarget.dataset.id) {
                    item.isAudits = e.detail ? '1' : '0';
                  }
                });
                if (that.data.isAudits === '') {
                  that.setData({ ApprovalList: arr });
                } else {
                  that.getApprovalListData();
                }
              } else {
                wx.showToast({
                  title: res.data.msg || '出错啦！',
                  icon: 'error',
                  duration: 2000
                })
              }
            },
            fail() {
              wx.showToast({
                title: '出错啦！',
                icon: 'error',
                duration: 2000
              })
            }
          })
        } else {
          console.log('用户点击取消');
        }
      }
    });
  },

  isPlacementTab(e) {
    let { active } = this.data;
    if (e.currentTarget.dataset.id === 0) {
      if (active.includes(0)) { active = active.filter(item => item !== 0 && item !== 1 && item !== 5); console.log(active); }
      else { active = active.filter(item => item !== 1 && item !== 5); active.push(0); }
      this.setData({ active });
    } else if (e.currentTarget.dataset.id === 1) {
      if (active.includes(1)) { active = active.filter(item => item !== 0 && item !== 1 && item !== 5); }
      else { active = active.filter(item => item !== 0 && item !== 5); active.push(1); }
      this.setData({ active });
    } else if (e.currentTarget.dataset.id === 2) {
      if (active.includes(2)) { active = active.filter(item => item !== 2 && item !== 3 && item !== 5); }
      else { active = active.filter(item => item !== 3 && item !== 5); active.push(2); }
      this.setData({ active });
    } else if (e.currentTarget.dataset.id === 3) {
      if (active.includes(3)) { active = active.filter(item => item !== 2 && item !== 3 && item !== 5); }
      else { active = active.filter(item => item !== 2 && item !== 5); active.push(3); }
      this.setData({ active });
    } else if (e.currentTarget.dataset.id === 4) {
      if (active.includes(4)) { active = active.filter(item => item !== 4 && item != 5); }
      else { active.push(4); }
      this.setData({ active });
    }
    if (e.currentTarget.dataset.id === 5 || this.data.active.length === 0) {
      this.setData({ active: [5] });
    }

    this.setData({ pageNum: 1, pageSize: 50, pageSizeIndex: 1 });
    this.getApprovalListData();
  },

  isDeliveryTab(e) {
    if (e.currentTarget.dataset.id === '') {
      this.setData({ isDelivery: '', isAudits: '', isPay: '' });
    } else if (e.currentTarget.dataset.id === 0 || e.currentTarget.dataset.id === 1) {
      this.setData({ isDelivery: e.currentTarget.dataset.id, isAudits: '', isPay: '' });
    } else if (e.currentTarget.dataset.id == 2) {
      this.setData({ isDelivery: '', isAudits: '0', isPay: '' });
    } else if (e.currentTarget.dataset.id == 3) {
      this.setData({ isDelivery: '', isAudits: '1', isPay: '' });
    } else if (e.currentTarget.dataset.id == 4) {
      this.setData({ isDelivery: '', isAudits: '', isPay: 0 });
    }
    this.setData({ pageNum: 1, pageSize: 50, pageSizeIndex: 1 });
    this.getApprovalListData();
  },
  clearSearch() {
    this.setData({ searchTagList: [] });
    this.childComponent = this.selectComponent("#moneySearch");
    this.childComponent.reset();
  },

  panel(e) {
    const arr = this.data.ApprovalList;
    arr.forEach(item => {
      if (e.currentTarget.dataset.id == item.id) item.isOpen = !item.isOpen;
    });
    this.setData({ ApprovalList: arr })
  },

  getDate() {
    let date = new Date();
    // 获取年份
    let year = date.getFullYear();
    // 获取月份，注意月份是从0开始的，所以需要加1
    let month = date.getMonth() + 1;
    // 获取日期
    let day = date.getDate();
    // 格式化月份、日期、分钟和秒数，如果小于10则在前面补0
    month = month < 10 ? '0' + month : month;
    day = day < 10 ? '0' + day : day;

    // 组合成需要的格式
    const formattedDate = `${year}-${month}-${day}`;
    this.setData({ nowDate: formattedDate });
  },

  getphone() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/login/getContact`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        let that = this;
        if (res.data.code == 0 && res.data.data.length) {
          that.setData({ telphone: res.data.data[0].tel })
        }
      }
    })
  },

  changeStar(e) {
    if(this.data.deptId != 3 || (this.data.deptId == 3 && this.data.admin != 1)) return;
    const id = e.currentTarget.dataset.id;
    let asterisk = e.currentTarget.dataset.asterisk;
    if(asterisk == '0') asterisk = '1';
    else asterisk = '0';
    this.updateAsterisk(id, asterisk);
  },

  updateAsterisk(id, asterisk) {
    const that = this;
    wx.request({
      url: `${app.globalData.baseUrl}/api/finance/update`,
      method: "POST",
      data: { id, asterisk },
      header: {
        "Content-Type": "application/json",
        'token': wx.getStorageSync('token'),
      },
      success: function (res) {
        if (res.data.code == 0) {
          that.getApprovalListData();
        } else {
          wx.showToast({
            title: res.data.msg || '系统异常',
          })
        }
      },
      fail() {
        wx.showToast({
          title: '出错啦！',
          icon: 'error',
          duration: 2000
        })
      }
    })
  },
})